package com.itboye.pondteam.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.WindowManager;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itboye.pondteam.R;
import com.itboye.pondteam.bean.DeviceListBean;
import com.itboye.pondteam.bean.PushModel;
import com.itboye.pondteam.bean.SearchDeviceInfo;
import com.itboye.pondteam.custom.ActivityInputWifiAndPass;
import com.itboye.pondteam.language.LanguageSettingUtil;
import com.itboye.pondteam.language.SwitchLanguageObservable;
import com.itboye.pondteam.pondteam.ActivityPondDeviceDetail;
import com.itboye.pondteam.pondteam.ActivityShouDong;
import com.itboye.pondteam.pondteam.ActivityStepFirst;
import com.itboye.pondteam.pondteam.ActivityStepThree;
import com.itboye.pondteam.pondteam.ActivityUvLamp;
import com.itboye.pondteam.pondteam.ActivityZiDong;
import com.itboye.pondteam.pondteam.AddPondDevice;
import com.itboye.pondteam.pondteam.DeviceRegisteringActivity;
import com.itboye.pondteam.pondteam.EditDeviceActivity;
import com.itboye.pondteam.pondteam.LocalAreaDeviceActivity;
import com.itboye.pondteam.pondteam.ManualAddDeviceActivity;
import com.itboye.pondteam.pondteam.MyDeviceActivity;
import com.itboye.pondteam.pondteam.VersionUpdateActivity;
import com.itboye.pondteam.utils.AppConfig;
import com.itboye.pondteam.utils.AqDeviceFind;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.utils.udp.AqSmartConfig;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by admin on 2016/12/6.
 */

public class MyApplication extends Application {

    private static RequestQueue queue;
    //    private LanguageSettingUtil languageSetting;
//    private SwitchLanguageObservable switchLangObs;
    public List<WeakReference<Activity>> activityList = new LinkedList<>();
    public static MyApplication instance;
    //    public AddDeviceNewActivity addDeviceUI;
//    public AddDeviceActivity mAddDeviceUi;
//    public ArrayList<AqDeviceInfo> mMyDeviceList = null;
//    public DeviceActivity mDeviceUi;
//    public Database mDatabase;
    public ActivityPondDeviceDetail pondDeviceDetailUI;//设备详情UI
    public MyDeviceActivity deviceListActivityUI;//设备列表UI
    public AddPondDevice addPondDeviceUI;//添加设备第一个界面
    public VersionUpdateActivity updateActivityUI;//固件更新
    private LanguageSettingUtil languageSetting;
    private SwitchLanguageObservable switchLangObs;
    public ActivityZiDong ziDongUI;
    public String languageType;
    public ActivityUvLamp uvLampUI;
    public ActivityShouDong shoudongUI;
    public ActivityStepFirst addDeviceFirst;
    public ActivityInputWifiAndPass addDeviceInputWifi;
    public AqSmartConfig aqSmartConfig;
    public ActivityStepThree addDeviceThird;
    public MyDeviceActivity mDeviceUi;
    public ManualAddDeviceActivity mManualAddDeviceUi;
    public LocalAreaDeviceActivity mLocalAreaDevice;
    private AqDeviceFind aqDeviceFind;
    public DeviceRegisteringActivity deviceRegisterUI;
    public DeviceListBean mEditDeviceInfo;
    public EditDeviceActivity mEditDeviceUi;

    public List<WeakReference<Activity>> getActivityList() {
        return activityList;
    }

    public void setActivityList(List<WeakReference<Activity>> activityList) {
        this.activityList = activityList;
    }
    public PushAgent mPushAgent;

    public static MyApplication getInstance() {
        return instance;
    }

    Gson gson;
    public static void setInstance(MyApplication instance) {
        MyApplication.instance = instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        aqSmartConfig = new AqSmartConfig(this);
        instance = this;
        gson=new Gson();
//        mLanDeviceList = new ArrayList<AqDeviceInfo>();
        queue = Volley.newRequestQueue(this);

        aqDeviceFind = new AqDeviceFind(mHandler);
        aqDeviceFind.start(AppConfig.Find_Device_Port);
//        mDatabase = new Database(this);
//        mMyDeviceList = mDatabase.getAllDeviceInfo();
//        aqDeviceFind=new AqDeviceFind(mHandler);
//        Logger.init("down");

        //设置默认语言为英文
        initLanguage();
        initUmeng();
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            SearchDeviceInfo msgObj = (SearchDeviceInfo) msg.obj;
            // 查找到一个设备
            findNewDeviceProcess(msgObj);
            return;

        }
    };

    private void initUmeng() {
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(true);

//		 sdk开启通知声音
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
////		 sdk关闭通知声音
//        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
////		 通知声音由服务端控制
//        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);

        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // 注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                System.out.println(">>>deviceToken" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {

                System.out.println(">>>deviceToken--" + s + "   s1" + s1);
            }
        });
        mPushAgent.setNotificationClickHandler(new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                super.dealWithCustomAction(context, msg);
                MAlert.alert("点击了" + msg);
            }

            @Override
            public void openActivity(Context arg0, UMessage msg) {
                //找出最上层可见状态的Activity
                Activity activityTop = null;
                for (WeakReference<Activity> activity : activityList) {
                    if (activity.get() != null) {
                        if (isForeground(getApplicationContext(),activity.get().getClass().getName())) {
                            activityTop = activity.get();
                        }
                    }

                }
                if (activityTop != null) {
                    PushModel model = gson.fromJson(msg.getRaw().toString(), PushModel.class);
                    AlertDialog.Builder alert = new AlertDialog.Builder(activityTop);
                    alert.setTitle(model.getBody().getTitle());
                    alert.setMessage((model.getBody().getText()));
                    Dialog dialog = alert.create();
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alert.show();
                }
            }
        });

//        mPushAgent.setMessageHandler(new UmengMessageHandler(){
//            @Override
//            public Notification getNotification(Context context, UMessage uMessage) {
//                AlertDialog.Builder alert=new AlertDialog.Builder(context);
//                alert.setMessage(uMessage.getRaw()+"");
//                Dialog dialog=alert.create();
//                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                alert.show();
//                return super.getNotification(context, uMessage);
//            }
//        });
    }
    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }
    private void initLanguage() {
        LanguageSettingUtil.init(this);// 初始化
        languageSetting = LanguageSettingUtil.get();// 检查是否已经初始化
        switchLangObs = new SwitchLanguageObservable();
        languageSetting.saveLanguage("en");
        LanguageSettingUtil.get().refreshLanguage();// 刷新
        switchLangObs.notifyObservers();
        languageType=languageSetting.getLanguage();
    }

    //    public LanguageSettingUtil getLanguageSetting() {
//        return languageSetting;
//    }
//
//    public SwitchLanguageObservable getSwitchLangObs() {
//        return switchLangObs;
//    }
    public LanguageSettingUtil getLanguageSetting() {
        return languageSetting;
    }

    public SwitchLanguageObservable getSwitchLangObs() {
        return switchLangObs;
    }

    public void addActivity(Activity activity) {
        activityList.add(new WeakReference<Activity>(activity));
    }
    public ArrayList<SearchDeviceInfo> mLanDeviceList = new ArrayList<>();

    private void findNewDeviceProcess(SearchDeviceInfo deviceInfo) {
        // 排除无效信息
        if (deviceInfo == null) {
            return;
        }
        if (deviceInfo.getPwd().equals("")) {
            // 屏蔽空密码局域网设备
            return;
        }
        // 局域网设备列表刷新
        boolean lanIsChange = true;
        boolean lanIsNewDevice = true;
        for (int i = 0; i < mLanDeviceList.size(); i++) {
            SearchDeviceInfo d = mLanDeviceList.get(i);
            if (d.getDid().equals(deviceInfo.getDid())) {
                lanIsNewDevice = false;
            } else {
                lanIsNewDevice = true;
                break;
            }
        }
        if (addDeviceThird != null) {
//            if (lanIsNewDevice) {
            addDeviceThird.findNewDeviceInfo(deviceInfo);
//            }
        }
        if (deviceRegisterUI != null) {
//            if (lanIsNewDevice) {
            deviceRegisterUI.findNewDeviceInfo(deviceInfo);
//            }
        }
        if (lanIsNewDevice) {
            // 添加新设备信息到局域网设备信息列表
            mLanDeviceList.add(deviceInfo);

        }
        if (mLocalAreaDevice != null) {
            mLocalAreaDevice.refreshDeviceList();
        }
    }

    // 遍历所有Activity并finish
    public void exit() {
        for (WeakReference<Activity> activity : activityList) {
            if (activity.get() != null) {
                activity.get().finish();
            }

        }
        System.exit(0);
    }

    /**
     * @return the queue
     */
    public static RequestQueue getQueue() {
        return queue;
    }

    //
    public static <T> void addRequest(Request<T> request) {
        request.addMarker("itboye");
        getQueue().add(request);
    }
}
